<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" :title="`${operationType}百业信息`">
        发布、修改服务信息(服务：主要是针对水管维修、家电清洗等常见，提供长期服务的服务方式)。平台发布的服务，一旦提交默认都是为发布状态，在网页、小程序、App端都可以查看到。(系统用户、系统管理员共用一张用户表)
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-3 proCard">
      <n-grid cols="1 s:1 m:2 l:2 xl:4 2xl:4" responsive="screen">
        <n-grid-item offset="0 s:0 m:0 l:0 xl:1 2xl:0" span="0 s:1 m:2 l:2 xl:2 2xl:2">
          <n-form
            ref="formRef"
            :label-width="80"
            :model="formValue"
            :rules="rules"
            class="py-8"
            label-placement="left"
          >
            <n-form-item label="服务标题" path="title">
              <n-input v-model:value="formValue.title" placeholder="请输入一个吸引人的标题" />
            </n-form-item>
            <n-form-item label="服务分类" path="category_id">
              <n-tree-select
                multiple
                checkable
                filterable
                :clear-filter-after-select="true"
                key-field="id"
                label-field="name"
                :options="categoryTree"
                clearable
                v-model:value="formValue.category_ids"
              />
            </n-form-item>
            <n-form-item label="服务简介" path="description">
              <n-input
                v-model:value="formValue.description"
                placeholder="请输入要发布的内容(详情)"
                type="textarea"
                :autosize="{
                  minRows: 5,
                  maxRows: 10,
                }"
              />
            </n-form-item>
            <n-form-item label="服务详情" id="details">
              <QuillEditor
                ref="quillEditor"
                :options="options"
                v-model:content="formValue.details"
                style="height: 350px"
                @ready="readyQuill"
                class="quillEditor"
              />
            </n-form-item>
            <n-form-item label="联系人" path="contact">
              <n-input
                v-model:value="formValue.contact"
                placeholder="请输入联系人称呼，例如:苟先生"
              />
            </n-form-item>
            <n-form-item label="联系电话" path="phone">
              <n-input v-model:value="formValue.phone" placeholder="电话号码" />
            </n-form-item>
            <div style="margin-left: 80px">
              <n-space>
                <n-button type="primary" @click="formSubmit">提交发布</n-button>
                <n-button @click="resetForm">重置</n-button>
              </n-space>
            </div>
          </n-form>
        </n-grid-item>
      </n-grid>
    </n-card>
  </div>
</template>

<script lang="ts">
  export default {
    name: 'BasicForm',
  };
</script>
<script lang="ts" setup>
  import { ref, unref, reactive, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useMessage, FormRules } from 'naive-ui';
  import { addService, editService, getService, serviceCategoryTree } from '@/api/service/service';
  import { useTabs } from '@/hooks/web/useTags';
  // 引入quill富文本编辑器
  import { QuillEditor } from '@vueup/vue-quill';
  import '@vueup/vue-quill/dist/vue-quill.snow.css';
  const quillEditor = ref();
  // quill配置信息
  const options = reactive({
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'], // toggled buttons
        ['blockquote', 'code-block'],

        [{ header: 1 }, { header: 2 }], // custom button values
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
        [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
        [{ direction: 'rtl' }], // text direction

        [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
        [{ header: [1, 2, 3, 4, 5, 6, false] }],

        [{ color: [] }, { background: [] }], // dropdown with defaults from theme
        [{ font: [] }],
        [{ align: [] }],
        ['clean'],
        ['image'],
      ],
    },
    theme: 'snow',
    placeholder: '输入您喜欢的内容吧！',
  });

  function readyQuill() {
    console.log('Quill准备好了');
  }

  function getHtmlVal() {
    return quillEditor.value.getHTML();
  }

  const { closeCurrent } = useTabs();
  // 通过route，获取页面提交过来的参数
  const route = useRoute();
  const router = useRouter();
  const operationType = ref('新增');
  // const globSetting = useGlobSetting();
  // const { uploadUrl } = globSetting;

  const rules: FormRules = {
    category_ids: {
      required: true,
      message: '请选择所属分类',
    },
    title: {
      required: true,
      message: '请输入信息标题',
      trigger: 'blur',
    },
    description: {
      required: true,
      message: '请输入要发布的内容',
      trigger: ['input'],
    },
    phone: [
      {
        required: true,
        message: '请输入预约备注',
        trigger: 'blur',
      },
      {
        validator: validatePhoneNumber,
        message: '输入手机号码不正确',
        trigger: 'blur',
      },
    ],
  };

  const formRef: any = ref(null);
  const categoryTree = ref([]);
  const message = useMessage();

  const defaultValueRef = (): {
    id: null | number;
    category_ids: null | Array<number>;
    title: string;
    description: string;
    details: string;
    contact: string;
    phone: string;
  } => ({
    id: null,
    category_ids: [],
    title: '',
    description: '',
    details: '',
    contact: '',
    phone: '',
  });

  // 需要提交的表单
  let formValue = reactive(defaultValueRef());
  function formSubmit() {
    // 获取quill编辑器,并赋值给details字段
    formValue.details = getHtmlVal();
    formRef.value.validate((errors) => {
      if (!errors) {
        if (!formValue.id) {
          // 新增信息
          addService(formValue)
            .then(() => {
              message.success('保存成功!');
              closeCurrent();
              router.push({ name: 'service_list' });
            })
            .catch(() => {
              message.error('保存失败!');
            });
        } else {
          // 修改服务
          editService(formValue)
            .then(() => {
              message.success('保存成功!');
              closeCurrent();
              // 跳转到list页面
              router.push({ name: 'information_list' });
            })
            .catch(() => {
              message.error('保存失败!');
            });
        }
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  function resetForm() {
    formRef.value.restoreValidation();
    formValue = Object.assign(unref(formValue), defaultValueRef());
  }

  function validatePhoneNumber(rule: FormItemRule, value: string): boolean {
    const phoneRegex = /^1[3-9]\d{9}$/; // 示例: 简单的中国大陆手机号码正则表达式
    if (phoneRegex.test(value)) {
      return true;
    } else {
      return false;
    }
  }

  async function getServiceCategory() {
    const cateTree = await serviceCategoryTree();
    categoryTree.value = cateTree;
  }

  async function loadService(id) {
    const information = await getService(id);
    // 将获取到的information赋值给formValue
    Object.keys(information).forEach((key) => {
      if (formValue.hasOwnProperty(key)) {
        formValue[key] = information[key];
      }
    });
    // 将details赋值给富文本编辑器
    // quillEditor.value.setHTML();
  }

  onMounted(() => {
    // 加载分类树形结构
    getServiceCategory();
    // 如果打开页面有params.id参数，那么就查询相应的百业信息
    if (route.query.id) {
      loadService(route.query.id);
      operationType.value = '修改';
    }
  });
</script>

<style lang="less">
  .n-form-item {
    .n-form-item-blank {
      display: block !important;
    }
  }
</style>
